{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 异常\n",
    "- 广义的错误是指分为异常和错\n",
    "- 异常时语法逻辑正确的情况下出现的问题，不可避免\n",
    "- 在python中，异常时一种类，可以处理和使用\n",
    "- 异常的基本语法：\n",
    "\t- try： +内容\n",
    "\t- except 异常类 as e:   print(e)   这个是必须的，可以有一个或者多个\n",
    "\t- else: 无异常时执行的代码   （可选）\n",
    "\t- finally : 一定会执行（可选）\n",
    "- tips:\n",
    "\t- Exception 时所有所有异常类型的基类\n",
    "\t- 捕获异常时需要把子类异常放在父类异常前面"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n\nfinally\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "     a = [1,2,3]\n",
    "     b = 2\n",
    "     # print(a[3])\n",
    "     # c = b/0\n",
    "     raise Exception    # 自己抛出异常,即使没有异常也会抛出\n",
    "except IndexError as e:\n",
    "    print(e)\n",
    "# 能够捕获所有的异常\n",
    "except Exception as e :\n",
    "    print('0')\n",
    "    print(e)\n",
    "else:\n",
    "    print('no error')\n",
    "finally:\n",
    "    print('finally')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是一个自定义异常\ndivision by zero\n"
     ]
    }
   ],
   "source": [
    "# 自定义异常\n",
    "class powerException(Exception):\n",
    "    print('这是一个自定义异常')\n",
    "try:\n",
    "    print(1/0)\n",
    "except ZeroDivisionError as e:\n",
    "    print(e)\n",
    "except powerException as e:\n",
    "    print(e)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
